#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.shortcuts import render
from django.shortcuts import redirect

from django.shortcuts import HttpResponse
from repository import models
from utils.pagination import Page
from django.db.models import F
from django.urls import reverse

import json


def index(request, **kwargs):
    """
    博客首页，展示全部博文
    """
    p = request.GET.get('p')
    current_page = int(p if p else 1)
    per_page_count = 3
    data_count = models.Article.objects.filter(**kwargs).prefetch_related('blog').count()
    my_page = Page(
        current_page=current_page,
        data_count=data_count,
        per_page_count=per_page_count,
        pager_num=5,
    )
    article_list = models.Article.objects.filter(**kwargs).prefetch_related('blog').all()[my_page.start:my_page.end]
    if kwargs.get('article_type'):
        page_str = my_page.page_str('/all/%s.html'%kwargs.get('article_type'))
    else:
        page_str = my_page.page_str('/')

    article_type_list = models.Article.type_choices

    user_obj = None
    if request.session.get('nid'):
        user_obj = models.UserInfo.objects.filter(nid=request.session.get('nid')).select_related('blog').first()

    top_up = models.Article.objects.prefetch_related('blog').all().order_by('-up_count')[:5]
    comment_up = models.Article.objects.prefetch_related('blog').all().order_by('-comment_count')[:5]
    res_dict = {
                'article_list': article_list,
                'article_type_list':article_type_list,
                'args': kwargs,
                'page_str': page_str,
                'user_obj': user_obj,
                'top_up': top_up,
                'comment_up': comment_up,
                }
    return render(request, 'index.html', res_dict)


def home(request, site):
    """
    博主个人首页
    Attributes:
       site: 博主的网站后缀如：http://xxx.com/wupeiqi.html
    """
    p = request.GET.get('p')
    current_page = int(p if p else 1)
    per_page_count = 5
    blog_obj = models.Blog.objects.filter(site=site).select_related('user').first()
    tag_list = models.Tag.objects.filter(blog_id=blog_obj.nid).prefetch_related('article_set').all()
    category_list = models.Category.objects.filter(blog_id=blog_obj.nid).prefetch_related('article_set').all()
    data_filter = models.Article.objects.raw(
        'select nid, count(nid) as num,strftime("%%Y-%%m",create_time) as ctime from '
        'repository_article where blog_id =%s group by strftime("%%Y-%%m",create_time)',params=[blog_obj.nid, ]
    )

    data_count = models.Article.objects.filter(blog=blog_obj).count()
    my_page = Page(
        current_page=current_page,
        data_count=data_count,
        per_page_count=per_page_count,
        pager_num=5,
    )
    article_list = models.Article.objects.filter(blog=blog_obj).all()[my_page.start:my_page.end]
    url = reverse('home',kwargs={'site': site})
    page_str = my_page.page_str(url)

    res_dict = {
                'blog': blog_obj,
                'tag_list': tag_list,
                'category_list': category_list,
                'data_filter': data_filter,
                'article_list':article_list,
                'page_str': page_str
                }

    return render(request, 'home.html', res_dict)


def filter(request, site, condition, val):
    """
    分类显示
    Attributes:
        request:
        site: 博客前缀
        condition: 分类条件，如: tag,date,category
        val: 分类值
    """
    user_home = models.Blog.objects.filter(site=site).select_related('user').first()
    if not user_home:
        return redirect('/')

    p = request.GET.get('p')
    current_page = int(p if p else 1)
    per_page_count = 5

    if condition == 'tag':
        data_count = models.Article.objects.filter(tags__title=val, blog=user_home).count()
        my_page = Page(
            current_page=current_page,
            data_count=data_count,
            per_page_count=per_page_count,
            pager_num=5,
        )
        article_list = models.Article.objects.filter(tags__title=val, blog=user_home).all()[my_page.start:my_page.end]

    elif condition == 'category':
        data_count = models.Article.objects.filter(category__title=val, blog=user_home).count()
        my_page = Page(
            current_page=current_page,
            data_count=data_count,
            per_page_count=per_page_count,
            pager_num=5,
        )
        article_list = models.Article.objects.filter(category__title=val, blog=user_home).all()[my_page.start:my_page.end]
    elif condition == 'date':
        data_count = models.Article.objects.filter(blog=user_home).extra(
            where=['strftime("%%Y-%%m",create_time)=%s'], params=[val, ]).count()
        my_page = Page(
            current_page=current_page,
            data_count=data_count,
            per_page_count=per_page_count,
            pager_num=5,
        )
        article_list = models.Article.objects.filter(blog=user_home).extra(
            where=['strftime("%%Y-%%m",create_time)=%s'], params=[val, ]).all()[my_page.start:my_page.end]
    else:
        article_list = []

    url = reverse('filter', kwargs={'site': site,'condition':condition,'val':val})
    page_str = my_page.page_str(url)

    tag_list = models.Tag.objects.filter(blog=user_home).prefetch_related('article_set').all()
    category_list = models.Category.objects.filter(blog=user_home).prefetch_related('article_set').all()
    data_filter = models.Article.objects.raw(
        'select nid, count(nid) as num,strftime("%%Y-%%m",create_time) as ctime from '
        'repository_article where blog_id =%s group by strftime("%%Y-%%m",create_time)', params=[user_home.nid, ]
    )

    res_dict = {
        'article_list': article_list,
        'blog': user_home,
        'data_filter':data_filter,    # 根据年月进行分类
        'tag_list': tag_list,    # 根据标签分类
        'category_list': category_list,    # 根据文章类型分类
        'page_str': page_str
    }

    return render(request, "home_summary_list.html", res_dict)


def detail(request, site, nid):
    """
    博文详细页
    Attributes:
        site: 博客前缀
        nid: article的nid
    """
    blog_obj = models.Blog.objects.filter(site=site).select_related('user').first()
    if not blog_obj:
        return redirect('/')

    article_obj = models.Article.objects.filter(blog_id=blog_obj.nid,nid=nid).prefetch_related('articledetail').first()
    if not article_obj:
        return redirect('/')
    else:
        article_obj.read_count += 1
        article_obj.save()

        data_filter = models.Article.objects.raw(
            'select nid, count(nid) as num,strftime("%%Y-%%m",create_time) as ctime from '
            'repository_article where blog_id =%s group by strftime("%%Y-%%m",create_time)', params=[blog_obj.nid, ]
        )
        tag_list = models.Tag.objects.filter(blog_id=blog_obj.nid).prefetch_related('article_set').all()
        category_list = models.Category.objects.filter(blog_id=blog_obj.nid).prefetch_related('article_set').all()

        p = request.GET.get('p')
        current_page = int(p if p else 1)  # 获取当前页
        per_page_count = 3  # 每页显示3条评论
        data_count = models.Comment.objects.filter(article_id=nid).count()

        my_page = Page(
            current_page=current_page,
            data_count=data_count,
            per_page_count=per_page_count,
            pager_num=5,
        )
        comment_list = models.Comment.objects.filter(article_id=nid)[my_page.start:my_page.end].prefetch_related('reply','user')
        page_str = my_page.page_str('/%s/%s.html'%(site,nid))
        res_dict = {
            'blog': blog_obj,
            'article': article_obj,
            'comment': comment_list,    # 评论列表
            'page_str': page_str,    # 分页项
            'data_filter':data_filter,    # 根据年月进行分类
            'tag_list': tag_list,    # 根据标签分类
            'category_list': category_list    # 根据文章类型分类
        }
        return render(request, 'home_detail.html',res_dict)


def submit_comment(request):
    """发表评论"""
    res_dict = {'status': True, 'errors': None, 'data': None}
    nid = request.POST.get('nid')
    content = request.POST.get('content').strip()
    if not content:
        res_dict['status'] = False
        res_dict['errors'] = '评论不能为空'
    else:
        models.Comment.objects.create(content=content,article_id=nid,user_id=request.session.get('nid'))
        models.Article.objects.filter(nid=nid).update(comment_count=F('comment_count')+1)
    return HttpResponse(json.dumps(res_dict))

def reply(request):
    """回复评论"""
    reply_to_nid = request.GET.get('reply_to')
    reply_to_obj = models.Comment.objects.filter(nid=reply_to_nid).prefetch_related('user').first()
    if request.method == "GET":
        return render(request, 'reply.html',{'reply_to': reply_to_obj})

    elif request.method == "POST":
        condition = {}
        condition['content'] = request.POST.get('content')
        condition['reply_id'] = request.POST.get('reply_to')
        condition['article_id'] = request.POST.get('article_id')
        condition['user_id'] = request.session.get('nid')
        models.Comment.objects.create(**condition)
        models.Article.objects.filter(nid=request.POST.get('article_id')).update(comment_count=F('comment_count') + 1)
        blog_obj = models.Blog.objects.filter(article__nid=request.POST.get('article_id')).first()
        site = blog_obj.site
        url = '/%s/%s.html'%(site,request.POST.get('article_id'))
        return redirect(url)


def updown(request):
    if request.method == "POST":
        res_dict = {'status': True, 'errors': None, 'data': None}
        user_id =  request.session.get('nid')
        if not user_id:
            res_dict['status'] = False
        else:

            article_id = request.POST.get('article_id')
            up = request.POST.get('up')
            if models.UpDown.objects.filter(article_id=article_id,user_id=user_id).exists():
                res_dict['status'] = False
            else:
                models.UpDown.objects.create(article_id=article_id,user_id=user_id,up=up)
                if up == '0':
                    models.Article.objects.filter(nid=article_id).update(down_count=F('down_count')+1)
                else:
                    models.Article.objects.filter(nid=article_id).update(up_count=F('up_count') + 1)
        return HttpResponse(json.dumps(res_dict))


def addfans(request):
    if request.method == "POST":
        res_dict = {'status': True, 'errors': None, 'data': None}
        user_id = request.session.get('nid')
        if not user_id:
            res_dict['status'] = False
        else:
            author_id = request.POST.get('author_id')
            print(type(user_id))
            print(type(author_id))
            if str(user_id) == str(author_id):
                res_dict['status'] = False
            else:
                if models.UserFans.objects.filter(user_id=author_id, follower=user_id).exists():
                    res_dict['status'] = False
                else:
                    models.UserFans.objects.create(user_id=author_id, follower_id=user_id)
        return HttpResponse(json.dumps(res_dict))




    print(request.POST.get('author_id'))
    print(request.session.get('nid'))
    pass
